#import "LoginUtils.h"
#import "WXApi.h"

@implementation LoginUtils

+(void)load {
    [self shareManager];
}
  
+(LoginUtils *)shareManager{
    static LoginUtils *instance = nil;
    static dispatch_once_t oneToken;
    dispatch_once(&oneToken,^{
        instance = [[LoginUtils alloc] init];
    });
    return instance;
}

- (instancetype)init{
    self = [super init];
    if (self) {
   
        [[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidFinishLaunchingNotification object:nil queue:nil usingBlock:^(NSNotification * _Nonnull note) {
            //初始化
            [self registerWX];
        }];
    }
    return self;
}

#pragma mark 注册微信
- (void)registerWX{
    [WXApi registerApp:wxAppID universalLink:wxUniversalLink];
}

#pragma mark 从微信分享过后点击返回应用的时候调用
- (void)onResp:(BaseResp *)resp{
    // =============== 获得的微信登录授权回调 ============
    if ([resp isMemberOfClass:[SendAuthResp class]])  {
        __weak typeof(self) wself = self;
        [LoginUtils userLoginWXWithResp:resp block:^(NSDictionary * _Nonnull sender) {
            !wself.callback?:wself.callback(sender);
        }];
    }
}

///登录接口
+(void)userLoginWithParam:(NSMutableDictionary *)param block:(void(^)(LoginModel *sender))block failure:(void(^)(NSString *error))failure{
    [[HttpHelp shareInstance] POSTHTTPV2:API_LOGIN_login parameters:param success:^(NSDictionary * _Nonnull dict, NSMutableArray * _Nonnull data) {
        block(data.firstObject);
    } failure:^(BOOL netErr, NSString * _Nonnull error) {
        failure(error);
    } withModel:[LoginModel class]];
}

///微信登录
+(void)userLoginWithWX:(UIViewController *)vc{
    SendAuthReq *req = [[SendAuthReq alloc] init];
    //用于保持请求和回调的状态，授权请求或原样带回
    req.state = @"wx_oauth_authorization_state";
    //授权作用域：获取用户个人信息
    req.scope = @"snsapi_userinfo";
    if([WXApi isWXAppInstalled]){//判断用户是否已安装微信App
        [WXApi sendReq:req completion:nil];
    }else{
        [WXApi sendAuthReq:req viewController:vc delegate:vc completion:^(BOOL success) {
            
        }];
//        [MBProgressHUD SG_showMBProgressHUDWithOnlyMessage:@"未安装微信应用或版本过低" delayTime:0.5];
    }
}

+(void)userLoginWXWithResp:(BaseResp *)resp block:(void(^)(NSDictionary *sender))block{
    SendAuthResp *aresp = (SendAuthResp *)resp;
    if (aresp.errCode != 0 ) {
        dispatch_async(dispatch_get_main_queue(), ^{
            [MBProgressHUD SG_showMBProgressHUDWithOnlyMessage:@"微信授权失败" delayTime:0.5];
        });
        return;
    }
    //授权成功获取 OpenId
    NSString *code = aresp.code;
    NSMutableDictionary *tempDic = [NSMutableDictionary new];
    [tempDic safeSetObject:code forKey:@"code"];
    block(tempDic.copy);
//    [self getWeiXinOpenId:code block:block];
}

//通过code获取access_token，openid，unionid
+(void)getWeiXinOpenId:(NSString *)code block:(void(^)(NSDictionary *sender))block{
    /*
     appid    是    应用唯一标识，在微信开放平台提交应用审核通过后获得
     secret    是    应用密钥AppSecret，在微信开放平台提交应用审核通过后获得
     code    是    填写第一步获取的code参数
     grant_type    是    填authorization_code
     */
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/oauth2/access_token?appid=%@&secret=%@&code=%@&grant_type=authorization_code",wxAppID,wechatSecret,code];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data1 = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        
        if (!data1) {
            [MBProgressHUD SG_showMBProgressHUDWithOnlyMessage:@"微信授权失败" delayTime:0.5];
            return ;
        }
        // 授权成功，获取token、openID字典
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data1 options:NSJSONReadingMutableContainers error:nil];
        NSString *access_token = dic[@"access_token"];
        NSString *openid= dic[@"openid"];
//        [[NSNotificationCenter defaultCenter] postNotificationName:@"weiChatBingding" object:openid];
        //         获取微信用户信息
        [self getUserInfoWithAccessToken:access_token WithOpenid:openid code:code block:block];
    });
}

+(void)getUserInfoWithAccessToken:(NSString *)access_token WithOpenid:(NSString *)openid code:(NSString *)code block:(void(^)(NSDictionary *sender))block{
    NSString *url =[NSString stringWithFormat:@"https://api.weixin.qq.com/sns/userinfo?access_token=%@&openid=%@",access_token,openid];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSURL *zoneUrl = [NSURL URLWithString:url];
        NSString *zoneStr = [NSString stringWithContentsOfURL:zoneUrl encoding:NSUTF8StringEncoding error:nil];
        NSData *data = [zoneStr dataUsingEncoding:NSUTF8StringEncoding];
        dispatch_async(dispatch_get_main_queue(), ^{
            // 获取用户信息失败
            if (!data) {
                [MBProgressHUD SG_showMBProgressHUDWithOnlyMessage:@"微信授权失败" delayTime:0.5];
                return ;
            }
            // 获取用户信息字典
            NSMutableDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
            //用户信息中没有access_token 我将其添加在字典中
            [dic safeSetObject:access_token forKey:@"token"];
            //openid 也加进来备用
            [dic safeSetObject:openid forKey:@"openid"];
            block(dic);
            //保存改用户信息(我用单例保存)
//            [AccountManager shareAccount].weixinInfo = dic;
          //微信返回信息后,会跳到登录页面,添加通知进行其他逻辑操作
//            [[NSNotificationCenter defaultCenter] postNotificationName:@"weiChatOK" object:nil];
        });
    });
}

@end
